package edu.bu.cs673.superkids123;

import java.io.IOException;
import java.security.GeneralSecurityException;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class SecurityUtil {
	/**
	 * @author Abdelghani Bhalla
	 */
	private static final char[] PASSWORD = "enfldsgbnlsngdlksdsgm".toCharArray();
	private static final byte[] SALT = { 	(byte) 0xde, (byte) 0x33, (byte) 0x10,
											(byte) 0x12, (byte) 0xde, (byte) 0x33, 
											(byte) 0x10, (byte) 0x12, };
	private static final String secretkey = "PBEWithMD5AndDES";
	private static final int iterationCount = 20;
/*
 * encryptProperty
 * @param proptery ex:password
 */
	public static String encryptProperty(String property)throws GeneralSecurityException {
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(secretkey);
		SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
		Cipher pbeCipher = Cipher.getInstance(secretkey);
		pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT,iterationCount ));
		return base64Encode(pbeCipher.doFinal(property.getBytes()));
	}

	private static String base64Encode(byte[] bytes) {
		return new BASE64Encoder().encode(bytes);
	}

	/*
	 * decryptProperty
	 * @param proptery ex:password
	 */
	public static String decryptProperty(String property)throws GeneralSecurityException, IOException {
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(secretkey);
		SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
		Cipher pbeCipher = Cipher.getInstance(secretkey);
		pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, iterationCount));
		return new String(pbeCipher.doFinal(base64Decode(property)));
	}

	private static byte[] base64Decode(String property) throws IOException {
		return new BASE64Decoder().decodeBuffer(property);
	}
}